<template>
	<xn-form-container title="导入固定资产" :width="550" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="推荐分公司" name="branch">
				<a-select
					v-model:value="formData.branch"
					placeholder="请选择推荐分公司"
					:options="branchCityOptions"
					:allowClear="true"
				/>
			</a-form-item>
			<a-form-item label="推荐部门" name="deptId">
				<DeptSelectTree v-model="formData.deptId" ref="deptSelectRef" />
			</a-form-item>
			<a-form-item label="资产分类" name="assetCategory">
				<a-select
					v-model:value="formData.assetCategory"
					placeholder="请选择资产分类"
					:options="assetsCategoryOptions"
					allowClear
				/>
			</a-form-item>
			<a-form-item label="上传文件" name="multipartFile">
				<!-- 文件上传区域 -->
				<a-upload-dragger
					:before-upload="beforeUpload"
					v-model:file-list="fileList"
					:show-upload-list="true"
					accept=".xlsx, .xls, .csv"
					:max-count="1"
				>
					<p class="ant-upload-drag-icon">
						<inbox-outlined />
					</p>
					<p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
					<p class="ant-upload-hint">支持单个上传，仅支持 Excel 或 CSV 文件</p>
				</a-upload-dragger>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import { required } from '@/utils/formRules'
	import tool from '@/utils/tool'
	import assetsAdminApi from '@/api/hrms/assets/admin/assetsAdminApi'
	import { message } from 'ant-design-vue'
	import { InboxOutlined } from '@ant-design/icons-vue'
	import DeptSelectTree from '@/components/Selector/deptSelectTree.vue'

	// 默认是关闭状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const branchCityOptions = tool.dictList('BRANCH_CITY')
	const assetsCategoryOptions = tool.dictList('ASSETS_CATEGORY')
	const fileList = ref([])
	const submitLoading = ref(false)

	// 表单数据
	const formData = ref({})

	// 默认要校验的
	const formRules = {
		branch: [required('请选择所属分支')],
		deptId: [required('请选择所属部门')],
		assetCategory: [required('请选择资产分类')]
	}

	// 上传前检查
	const beforeUpload = (file) => {
		// 检查文件类型是否为excel或csv
		const isExcelOrCSV =
			file.type.includes('spreadsheet') ||
			file.type.includes('csv') ||
			file.name.endsWith('.xlsx') ||
			file.name.endsWith('.xls') ||
			file.name.endsWith('.csv')

		if (!isExcelOrCSV) {
			message.error('只能上传 Excel 或 CSV 文件!')
			return false
		}

		fileList.value = [file]
		return false
	}

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		if (record) {
			formData.value = Object.assign({}, record)
		} else {
			// 新增时清空表单
			formData.value = {}
		}
		// 重置文件相关状态
		fileList.value = []
	}

	// 关闭抽屉
	const onClose = () => {
		formRef.value?.resetFields()
		fileList.value = []
		formData.value = {}
		visible.value = false
		submitLoading.value = false
	}

	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				if (fileList.value.length === 0) {
					message.error('请上传文件')
					return
				}
				submitLoading.value = true
				const submitData = new FormData()
				// 添加文件
				submitData.append('multipartFile', fileList.value[0].originFileObj)
				submitData.append(
					'fixedAssetsImportBo',
					new Blob([JSON.stringify(formData.value)], { type: 'application/json' })
				)
				assetsAdminApi
					.importExcel(submitData)
					.then(() => {
						message.success('导入成功')
						onClose()
						emit('successful')
					})
					.catch((error) => {
						message.error('导入失败: ' + (error.message || ''))
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {
				submitLoading.value = false
			})
	}

	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
